import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart' hide Action;

import 'edit_page/page.dart';
import 'global_store/state.dart';
import 'global_store/store.dart';
import 'index_page/page.dart';

// 创建应用根widget
/// 1.  创建简单路由, 并注册页面
/// 2.  对所需页面进行与 AppStore 的连接
/// 3.  对所需页面进行 Aop 增强
Widget createApp() {
  final AbstractRoutes routes = PageRoutes(
      pages: <String, Page<Object, dynamic>>{
        /// 在这里进行页面注册
        'edit': EditPage(),
        'index': IndexPage()
      },
      visitor: (String path, Page<Object, dynamic> page) {
        /// 只有特定范围的Page才需要建立和AppStore的连接关系
        /// 满足 Page<T>, T 是 GlobalBase 的子类
        if (page.isTypeof<GlobalBaseState>()) {
          /// 建立 AppStore 驱动 PageStore 的单向数据连接
          /// 1. 参数1 AppStore
          /// 2. 参数2 当 AppStore.state变化时, PageStore.state相应的变化
          page.connectExtraStore<GlobalState>(GlobalStore.store,
              (Object pageState, GlobalState appState) {
            final GlobalBaseState p = pageState;

            // 这里判断当颜色不同时, 进行操作
            if (p.themeColor != appState.themeColor) {
              // 判断传入的pageState是否允许克隆
              if (pageState is Cloneable) {
                // 克隆一份pageState
                final Object copy = pageState.clone();
                final GlobalBaseState newState = copy;

                // 变更颜色状态
                newState.themeColor = appState.themeColor;
                // 返回状态
                return newState;
              }
            }
            return pageState;
          });
        }

        /// AOP
        /// 页面可以有一些私有的 AOP 的增强, 全部页面都需要某些 AOP
        /// 公共的通用AOP, 通过遍历路由页面的形式统一加入
        page.enhancer.append(
          /// View AOP
          viewMiddleware: <ViewMiddleware<dynamic>>[safetyView<dynamic>()],

          /// Adapter AOP
          adapterMiddleware: <AdapterMiddleware<dynamic>>[
            safetyAdapter<dynamic>()
          ],

          /// Effect AOP
          effectMiddleware: [
            _pageAnalyticsMiddleware<dynamic>(),
          ],

          /// Store AOP
          middleware: <Middleware<dynamic>>[
            logMiddleware<dynamic>(tag: page.runtimeType.toString()),
          ],
        );
      });
  return MaterialApp(
    title: 'Fluro',
    debugShowCheckedModeBanner: false,
    theme: ThemeData(
      primarySwatch: Colors.blue,
    ),

    /// 设置首页
    home: routes.buildPage('index', null),
    onGenerateRoute: (RouteSettings settings) {
      return MaterialPageRoute<Object>(builder: (BuildContext context) {
        return routes.buildPage(settings.name, settings.arguments);
      });
    },
  );
}

/// 简单的 Effect AOP
/// 只针对页面的生命周期进行打印
EffectMiddleware<T> _pageAnalyticsMiddleware<T>({String tag = 'redux'}) {
  return (AbstractLogic<dynamic> logic, Store<T> store) {
    return (Effect<dynamic> effect) {
      return (Action action, Context<dynamic> ctx) {
        if (logic is Page<dynamic, dynamic> && action.type is Lifecycle) {
          print('${logic.runtimeType} ${action.type.toString()} ');
        }
        return effect?.call(action, ctx);
      };
    };
  };
}
